#include "SFMLMap.h"

Image SFMLMap::tilesetImage = Image();

SFMLMap::SFMLMap()
{
   show_selector = false;
   active_selector = false;
   spriteSelector = Sprite();
}

SFMLMap::SFMLMap(RenderWindow* p_App, Map* p_parent)
{
   show_selector = false;
   active_selector = false;
   App = p_App;
   parent = p_parent;
   spriteSelector = Sprite();
   cutTileset();
}

IntRect SFMLMap::indice_to_rect(int i)
{
   int iCol = indice_to_map_coord(i, parent->mapDim.width).iCol;
   int iLig = indice_to_map_coord(i, parent->mapDim.width).iLig;
   return IntRect(iCol*TILE_DIM+1,iLig*TILE_DIM+1,iCol*TILE_DIM+TILE_DIM,iLig*TILE_DIM+TILE_DIM);
}


void SFMLMap::cutTileset()
{
   for(int iLig = 0 ; iLig < parent->mapDim.height ; iLig++)
      for(int iCol = 0 ; iCol < parent->mapDim.width ; iCol++)
      {
         Sprite curr;
         curr.SetImage(tilesetImage);
         curr.SetPosition(parent->coord_on_screen[L_SOL][iLig][iCol].x,parent->coord_on_screen[L_SOL][iLig][iCol].y);
         curr.SetSubRect(indice_to_rect(parent->tile_on_case[L_SOL][iLig][iCol]));
         IntRect a = indice_to_rect(parent->tile_on_case[L_SOL][iLig][iCol]);
         sprite_on_layer[L_SOL][iLig][iCol] = curr;
      }
}

void SFMLMap::showSelector()
{
   show_selector = true;
}

void SFMLMap::unshowSelector()
{
   show_selector = false;
}

void SFMLMap::activeSelector()
{
   active_selector = true;
}

void SFMLMap::unactiveSelector()
{
   active_selector = false;
}

void SFMLMap::initSelector(sf::Color c)
{
   Selector = Shape::Rectangle(parent->start.x,parent->start.y,parent->start.x+TILE_DIM-1,parent->start.y+TILE_DIM-1,Color(0,0,0,0),3,c);
   posSelector = map_coord();
}

bool SFMLMap::valide(map_coord c)
{
   return c.iLig >= 0 && c.iLig < parent->mapDim.height && c.iCol >= 0 && c.iCol < parent->mapDim.width;
}

void SFMLMap::moveSelector(const int iDir)
{
   if(active_selector)
   {
      map_coord new_coord = map_coord(posSelector.iLig+dir[iDir][0],posSelector.iCol+dir[iDir][1]);
      if(valide(new_coord))
      {
         posSelector = new_coord;
         Selector.Move(dir[iDir][1]*TILE_DIM+parent->space_w*dir[iDir][1],dir[iDir][0]*TILE_DIM+parent->space_h*dir[iDir][0]);
      }
      spriteSelector.SetPosition(parent->start.x+posSelector.iCol*TILE_DIM,parent->start.y+posSelector.iLig*TILE_DIM);
   }
}

void SFMLMap::setSpriteOnSelector(Sprite spr)
{
   spriteSelector = spr;
   spriteSelector.SetPosition(parent->start.x+posSelector.iCol*TILE_DIM,parent->start.y+posSelector.iLig*TILE_DIM);
   spriteSelector.SetImage(tilesetImage);
}

void SFMLMap::draw()
{
   for(int iLig = 0 ; iLig < parent->mapDim.height ; iLig++)
      for(int iCol = 0 ; iCol < parent->mapDim.width ; iCol++)
         App->Draw(sprite_on_layer[L_SOL][iLig][iCol]);
   if(show_selector)
   {
      App->Draw(Selector);
      App->Draw(spriteSelector);
   }
}
